import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
//导入组件
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'
//配置路由
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta:{isLogin:true}
      },
      {
        path: '/',
        redirect:'/home'
      }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  //*代表任何路径。路由默认从上往下匹配，如果可以匹配则加载路由，如果不可以匹配则继续往下匹配，直到最后一个路由
  {
    path: '*',
    redirect:'/notfound'
  }
]
const originPush = VueRouter.prototype.push
VueRouter.prototype.push = function (a,resolve,reject) {
  if (resolve||reject) {
    return originPush.call(this,a,resolve,reject)
  } else {
    return originPush.call(this, a).catch(err => {
      
    })
  }
}

const router = new VueRouter({
  routes
})
// router.push = function (a,resolve,reject) {
//   if (resolve || reject) {
//     return VueRouter.prototype.push.call(this,a,resolve,reject)
//   } else {
//     return VueRouter.prototype.push.call(this,a).catch(err => {
      
//     })
//   }
// }
//导入token
import { getToken } from '@/utils/token.js'

router.beforeEach((to, from, next) => {
  //to:目标路由 要跳转到哪里
  //from: 来源路由  从哪个路由跳转
  if (to.meta.isLogin&&!getToken()) {
      next({path:'/login'})
  } else {
    next()
  }
})


export default router
